#include "mscene.h"
#include <QtGui>
#include<Util/cstate.h>
#include<QPen>
mScene::mScene(QObject *parent)
    : QGraphicsScene(parent)
{
    myMode=MoveItem;
    line=0;
    textItem=0;
    myItemColor = "#FAFAD2";
    myItemClickColor = "#EEE8AA";
    myItemDoubleClickColor  = "#BDB76B";
    myTextColor = "#666666";
    myLineColor = "#666666";
    myItemBorderLineColor="#999999";
    myDataManger=new mDataManager();
    //connect(this,SIGNAL(focusItemChanged(QGraphicsItem*,QGraphicsItem*,Qt::FocusReason)),this,SLOT(on_focusItemChanged(QGraphicsItem*,QGraphicsItem*,Qt::FocusReason)));

}

mScene::~mScene()
{

}


void mScene::setLineColor(const QColor &color)
{
    myLineColor = color;
    if (isItemChange(mArrow::Type)) {
        mArrow *item =
            qgraphicsitem_cast<mArrow *>(selectedItems().first());
        item->setColor(myLineColor);
        update();
    }
}

void mScene::setTextColor(const QColor &color)
{
    myTextColor = color;
    if (isItemChange(mText::Type)) {
        mText *item =
            qgraphicsitem_cast<mText *>(selectedItems().first());
        item->setDefaultTextColor(myTextColor);
    }
}

void mScene::setItemColor(const QColor &color)
{
    myItemColor = color;
    if (isItemChange(mProcess::Type)) {
        mProcess *item =
            qgraphicsitem_cast<mProcess *>(selectedItems().first());
        item->setBrush(myItemColor);
    }
}

void mScene::setFont(const QFont &font)
{
    myFont = font;

    if (isItemChange(mText::Type)) {
        mText *item =
            qgraphicsitem_cast<mText *>(selectedItems().first());
        //At this point the selection can change so the first selected item might not be a DiagramTextItem
        if (item)
            item->setFont(myFont);
    }
}

void mScene::setMode(Mode mode)
{
    myMode = mode;
}

void mScene::editorLostFocus(mText *item)
{
    QTextCursor cursor = item->textCursor();
    cursor.clearSelection();
    item->setTextCursor(cursor);

    if (item->toPlainText().isEmpty()) {
        removeItem(item);
        item->deleteLater();
    }
}

bool mScene::isItemChange(int type)
{
    foreach (QGraphicsItem *item, selectedItems()) {
        if (item->type() == type)
            return true;
    }
    return false;
}

bool mScene::deleteItemFromData(int id)
{
    myDataManger->DeleteProcess(id);
    return true;
}

bool mScene::deleteArrowFromData(int id)
{
    myDataManger->DeleteArrow(id);
    return true;
}

bool mScene::saveDataToXMLFile(QString path)
{
    return myDataManger->SaveFile(path);
}

void mScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
    if (mouseEvent->button() != Qt::LeftButton)
        return;

    QString butterfly_fn;
    QString Itemext="";

    butterfly_fn="";
    Itemext="AirPatrol";

    //ImageItem* imageItem;
    mProcess *item;
    QPointF posPointer;

    //点击变色
    foreach (QGraphicsItem *item, items(mouseEvent->scenePos())) {
      QMap<QString,mProcess *>::iterator i;
        for (i = ProcessItemMap.begin(); i != ProcessItemMap.end(); ++i)
            if(i.value()->pos()==item->pos()){
                if(lastDoubleClickState!=NULL && lastDoubleClickState!=i.value()){
                    lastDoubleClickState->setBrush(this->myItemColor);
                }
                if(lastDoubleClickState!=i.value()){
                    i.value()->setBrush(QColor(myItemClickColor));
                    lastDoubleClickState=i.value();
                }
                break;
            }

    }
    if(items(mouseEvent->scenePos()).size()==0&&this->items().size()!=0){
        if(lastDoubleClickState!=NULL){
            lastDoubleClickState->setBrush(this->myItemColor);
        }
}

    switch (myMode) {
    case InsertItem:
        item = new mProcess(myDataManger->GetProcessID());
        item->setBrush(myItemColor);

        addItem(item);

        item->setPos(mouseEvent->scenePos());
        item->setZValue(1000);
        emit itemInserted(item);

        textItem = new mText(item);
        textItem->setFont(myFont);
        textItem->setTextInteractionFlags(Qt::TextEditorInteraction);
        textItem->setZValue(1000);
        connect(textItem, SIGNAL(lostFocus(DiagramTextItem*)),
            this, SLOT(editorLostFocus(DiagramTextItem*)));
        connect(textItem, SIGNAL(selectedChange(QGraphicsItem*)),
            this, SIGNAL(itemSelected(QGraphicsItem*)));
        addItem(textItem);


        textItem->setDefaultTextColor(myTextColor);

        posPointer.setX(mouseEvent->scenePos().x()-24-butterfly_fn.length()*2);
        posPointer.setY(mouseEvent->scenePos().y()+24);
        textItem->setPos(posPointer);
        textItem->setPlainText(Itemext);

        item->addText(textItem);
        emit textInserted(textItem);

        myDataManger->AddProcess(item->GetMyId(),item->pos(),Itemext,myTextColor);

        break;
        //! [6] //! [7]
    case InsertLine:
        line = new QGraphicsLineItem(QLineF(mouseEvent->scenePos(),
            mouseEvent->scenePos()));
        line->setPen(QPen(myLineColor, 2));
        addItem(line);
        break;
        //! [7] //! [8]
    case InsertText:
        textItem = new mText(item);
        textItem->setFont(myFont);
        textItem->setTextInteractionFlags(Qt::TextEditorInteraction);
        textItem->setZValue(1000.0);
        connect(textItem, SIGNAL(lostFocus(DiagramTextItem*)),
            this, SLOT(editorLostFocus(DiagramTextItem*)));
        connect(textItem, SIGNAL(selectedChange(QGraphicsItem*)),
            this, SIGNAL(itemSelected(QGraphicsItem*)));
        addItem(textItem);
        textItem->setDefaultTextColor(myTextColor);
        textItem->setPos(mouseEvent->scenePos());
        emit textInserted(textItem);
        //! [8] //! [9]
    default:
        ;
    }
    QGraphicsScene::mousePressEvent(mouseEvent);
}

void mScene::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
    if (myMode == InsertLine && line != 0) {
        QLineF newLine(line->line().p1(), mouseEvent->scenePos());
        line->setLine(newLine);
    }
    else if (myMode == MoveItem) {
        QGraphicsScene::mouseMoveEvent(mouseEvent);
    }
}

void mScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
    if (line != 0 && myMode == InsertLine) {
        QList<QGraphicsItem *> startItems = items(line->line().p1());
        if (startItems.count() && startItems.first() == line)
            startItems.removeFirst();
        QList<QGraphicsItem *> endItems = items(line->line().p2());
        if (endItems.count() && endItems.first() == line)
            endItems.removeFirst();

        removeItem(line);
        delete line;
        //! [11] //! [12]

        if (startItems.count() > 0 && endItems.count() > 0 &&
            startItems.first()->type() == mProcess::Type &&
            endItems.first()->type() == mProcess::Type &&
            startItems.first() != endItems.first()) {
                mProcess *startItem =
                    qgraphicsitem_cast<mProcess*>(startItems.first());
                mProcess *endItem =
                    qgraphicsitem_cast<mProcess *>(endItems.first());
                mArrow *arrow = new mArrow(startItem, endItem,myDataManger->GetArrowID());
                arrow->setColor(myLineColor);
                startItem->addArrow(arrow);
                endItem->addArrow(arrow);
                arrow->setZValue(-1000.0);
                addItem(arrow);
                //myDataManger->AddArrow(arrow->GetMyID(),startItem->GetMyId(),endItem->GetMyId(),myLineColor);
                arrow->updatePosition();
        }
    }
    //! [12] //! [13]
    line = 0;

    QGraphicsScene::mouseReleaseEvent(mouseEvent);
}

void  mScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *mouseEvent){
     if (mouseEvent->button() != Qt::LeftButton){
         return ;
     }

         foreach (QGraphicsItem *item, items(mouseEvent->scenePos())) {
           QMap<QString,mProcess *>::iterator i;
             for (i = ProcessItemMap.begin(); i != ProcessItemMap.end(); ++i)
                 if(i.value()->pos()==item->pos()){
                     i.value()->setBrush(QColor(myItemDoubleClickColor));
                     lastDoubleClickState=i.value();
                     emit  on_ModelState_doubleClicked(i.value()->getStateInfo());
                     break;
                 }

         }
         if(items(mouseEvent->scenePos()).size()==0&&this->items().size()!=0){
             if(lastDoubleClickState!=NULL){
                 lastDoubleClickState->setBrush(this->myItemColor);
             }
         }

    QGraphicsScene::mouseDoubleClickEvent(mouseEvent);
}

//添加步骤
void mScene::addProcessItem(QMap<QString ,QString> ActivityMap){
    //                QMapIterator<QString,QString> j(*Activitys->at(index));
    //                while(j.hasNext()){
    //                    j.next();
    //                    QString name="";
    //                    QString value="";
    //                    name=j.key();
    //                    value=j.value();
    //                    qWarning()<<"   "<<name<<":"<<value<<endl;
    //                  }


    mProcess *item;
    QPointF posPointer;
    QString ItemText=ActivityMap.value("ActivityName");
    qreal x=ActivityMap.value("PositionX").toInt();
    qreal y=ActivityMap.value("PositionY").toInt();
    bool hasInfo=false;
        item = new mProcess(myDataManger->GetProcessID());
        item->setBrush(myItemColor); //设置填充颜色
        QPen pen1;
        pen1.setColor(myItemBorderLineColor); //设置边线颜色
        item->setPen(pen1);
        for(int index=0;index<StateList->count();index++){
            if(ItemText==StateList->at(index)->getStateName()){
                   item->addInfo(StateList->at(index));
                   hasInfo=true;
                   break;
            }
        }
        if(!hasInfo){
            CState *state=new CState();
            item->addInfo(state);
        }
        item->setPos(x,y);
        item->setZValue(1000);
        emit itemInserted(item);

        textItem = new mText(item);
        textItem->setFont(myFont);
        textItem->setTextInteractionFlags(Qt::TextEditorInteraction);
        textItem->setZValue(1000);
        addItem(textItem);
        textItem->setDefaultTextColor(myTextColor);

        posPointer.setX(x-24);
        posPointer.setY(y+24);
        textItem->setPos(posPointer);
        textItem->setPlainText(ItemText);

        item->addText(textItem);
        addItem(item);
        //存储一下item
        ProcessItemMap.insert(ActivityMap.value("UniqueID"),item);
}
void mScene::addProcessItem(QString UniqueID,QString StateName,qreal x,qreal y){
    mProcess *item;
    QPointF posPointer;
    QString ItemText=StateName;
    bool hasInfo=false;
        item = new mProcess(myDataManger->GetProcessID());
        item->setBrush(myItemColor); //设置填充颜色
        QPen pen1;
        pen1.setColor(myItemBorderLineColor); //设置边线颜色
        item->setPen(pen1);
        for(int index=0;index<StateList->count();index++){
            if(ItemText==StateList->at(index)->getStateName()){
                   item->addInfo(StateList->at(index));
                   hasInfo=true;
                   break;
            }
        }
        if(!hasInfo){
            CState *state=new CState();
            item->addInfo(state);
        }
        item->setPos(x,y);
        item->setZValue(1000);
        emit itemInserted(item);

        textItem = new mText(item);
        textItem->setFont(myFont);
        textItem->setTextInteractionFlags(Qt::TextEditorInteraction);
        textItem->setZValue(1000);
        addItem(textItem);
        textItem->setDefaultTextColor(myTextColor);

        posPointer.setX(x-24);
        posPointer.setY(y+24);
        textItem->setPos(posPointer);
        textItem->setPlainText(ItemText);

        item->addText(textItem);
        addItem(item);
        //存储一下item
        ProcessItemMap.insert(UniqueID,item);
}

//添加箭头
void mScene::addArrowItem(QMap<QString ,QString> RuleMap){
    mProcess *startItem =
       ProcessItemMap.value(RuleMap.value("BeginActivityUniqueID"));
    mProcess *endItem =
        ProcessItemMap.value(RuleMap.value("EndActivityUniqueID"));
    mArrow *arrow = new mArrow(startItem, endItem,myDataManger->GetArrowID());
    arrow->setColor(myLineColor);
    startItem->addArrow(arrow);
    endItem->addArrow(arrow);
    arrow->setZValue(-1000.0);
    addItem(arrow);
    arrow->updatePosition();
}

void mScene::addArrowItem(QString StartStateUniqueID,QString EndStateUniqueID){
    mProcess *startItem =
       ProcessItemMap.value(StartStateUniqueID);
    mProcess *endItem =
        ProcessItemMap.value(EndStateUniqueID);
    mArrow *arrow = new mArrow(startItem, endItem,myDataManger->GetArrowID());
    arrow->setColor(myLineColor);
    startItem->addArrow(arrow);
    endItem->addArrow(arrow);
    arrow->setZValue(-1000.0);
    addItem(arrow);
    arrow->updatePosition();
}


void mScene::addAllInfo(QList<CState *> *DStateListMap){
    StateList=NULL;
    this->lastDoubleClickState=NULL;
    StateList=DStateListMap;
}

